package com.haizhi.crm.biz.task.message.handler;

import com.haizhi.crm.biz.constant.MessageStatus;
import com.haizhi.crm.biz.dao.MessageClientDao;
import com.haizhi.crm.biz.model.*;
import com.haizhi.crm.biz.service.MessageService;
import com.haizhi.crm.biz.service.MessageUserResourceService;
import com.haizhi.crm.biz.service.MessageUserService;
import com.haizhi.crm.biz.task.message.model.ContextDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Created by wangshan on 2018/5/29.
 */
@Component
public class PushHandler extends AbstractHandler<ContextDto> {

    @Autowired
    private MessageService messageService;

    @Autowired
    private MessageClientDao messageClientDao;

    @Autowired
    private MessageUserService messageUserService;

    @Autowired
    private MessageUserResourceService messageUserResourceService;


    @Override
    protected MsgResponse process(ContextDto data) {
        MessageDo messageDo = new MessageDo();
        messageDo.setMsgSource(data.getDatabases());
        messageDo.setMsgTitle(data.getTitle());
        messageDo.setMsgSchema(data.getMsgSchema());
        messageDo.setMsgKey(data.getDetailKey());
        messageDo.setMsgCategoryId(data.getMsgCategoryId());
        messageDo.setMsgSourceType(data.getEventType());
        messageDo.setCreatedDt(new Date());
        messageDo.setUpdatedDt(new Date());
        MessageDo messageDo1 = messageService.add(messageDo);
        data.setMsgId(messageDo1.getId());
        for (MessageClientDo messageClientDo : data.getMessageClientDos()) {
            messageClientDo.setMessageId(data.getMsgId());
            messageClientDao.save(messageClientDo);
        }
        for (MessageUserVo messageUserVo : data.getMessageUserVoMap().values()) {
            Long userId = messageUserVo.getUserId();
            MessageUserDo messageUserDo = new MessageUserDo();
            messageUserDo.setMsgId(data.getMsgId());
            messageUserDo.setStatus(MessageStatus.UNREAD);
            messageUserDo.setUserId(messageUserVo.getUserId());
            MessageUserDo messageUserDo1 = messageUserService.save(messageUserDo);
            for (MessageUserResourceDo messageUserResourceDo : messageUserVo.getMessageUserResourceDoList()) {
                messageUserResourceDo.setMessageUserId(messageUserDo1.getId());
                messageUserResourceService.save(messageUserResourceDo);
            }
        }

        return MsgResponse.success();
    }

}
